package com.hs.pre.sys.validate;

import java.io.UnsupportedEncodingException;
import java.util.logging.Logger;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.hs.pre.model.ProfileBean;
import com.hs.pre.model.UserBean;
import com.hs.pre.module.bardian.BardianDao;
import com.hs.pre.util.MD5;

public class LoginVali {
	/**
	 * Log4J Logger for this class
	 */
	private static final Logger logger = Logger.getLogger(LoginVali.class.getName());

	public ActionForward loginValiExecute(ActionMapping mapping,
			ActionForm form,
			HttpServletRequest request,
			HttpServletResponse response){
		/**
		 * 为true表示验证通过
		 */
		boolean succeed=false;
		/**
		 * 登录验证失败的错误信息
		 */
		try {
			
			/***
			 * 清楚该用户所有的 session 信息 
			 */
			request.getSession().invalidate();
			
			String message="";
			String username=request.getParameter("username");
			String password=request.getParameter("password");
			String saveCookie=request.getParameter("saveCookie");
			setCookie(username, password,saveCookie,null, response); //设置Cookie
			
			if(this.isSyntax(username, password,request)){
				if(!this.isAdministrator(username, password)){
					
					UserBean userBean =this.isLegalityUser(username, password, request);
					if(userBean != null)
					{
						succeed=true;
						this.initUser(userBean, request);
						this.initBardian(userBean.getUserId()+"", request);
						setCookie(username, password, saveCookie,"", response); //设置Cookie
					}
					else
					{
						request.setAttribute(ParameterDic.MESSAGE, HintParameter.ERRORLONGINUSER_DCPM);
					}
					
				}else{
					this.initAdministrator(request);
					succeed=true;
//					setCookie(username, password,saveCookie,null, response); //设置Cookie
				}
			}else {
				
			}
		} catch (Exception e) {
			// TODO 自动生成 catch 块
			request.setAttribute(ParameterDic.MESSAGE, HintParameter.ERRORSYS_DCPM);
			e.printStackTrace();
		}
		
		if(succeed){
			return mapping.findForward("pass");
		}else
			return mapping.findForward("error");
	}
	
	/**
	 * 个性设置初始化
	 * @param userId
	 * @param request
	 */
	private void initBardian(String userId,HttpServletRequest request)
	{
		BardianDao bardianDao = new BardianDao();
		try {
			ProfileBean profileBean = bardianDao.getBardianDao(userId);
			request.getSession().setAttribute(ParameterDic.USER_BARDIAN, profileBean);  //用户个性设置
		} catch (Exception e) {
			// TODO Auto-generated catch block
			this.logger.info("初始化个性设置失败!");
			e.printStackTrace();
		}
	}
	
	/**
	 * 
	 * 功能: 验证是否是超级管理员
	 * 作者: WXY
	 * 创建日期:2007-7-6
	 * @return
	 */
	private boolean isAdministrator(String username,String password)
	{
//		boolean flag=SystemAdministrator.isAdministrator(username,password);
		boolean flag=false;
		return flag;
	}
	

	/**
	 * 
	 * 功能:设置一个系统的Cookie
	 * 作者: shaokun305
	 * 创建日期:2007-9-20
	 * @param userName
	 * @param password
	 * @param SaveCookie
	 * @param response
	 */
	private void setCookie(String userName,String password,String saveCookie,String skId,HttpServletResponse response){
//		设置cookie
		if(null == skId)
			skId = "1";
		if(saveCookie!=null && saveCookie.trim().equals("yes")){
			Cookie userCookie=null;
				try {
					userCookie = new Cookie("uid", java.net.URLEncoder.encode(userName,"UTF-8"));
				} catch (UnsupportedEncodingException e) {
					// TODO 自动生成 catch 块
					e.printStackTrace();
				}
			Cookie passCookie = new Cookie("upss",password);
			Cookie skIdObj = new Cookie("skId",skId);
			//cookie默认保存15天
			userCookie.setMaxAge(60*60*24*15);
			passCookie.setMaxAge(60*60*24*15);
			skIdObj.setMaxAge(60*60*24*15);
			userCookie.setPath("/");
			passCookie.setPath("/");
			skIdObj.setPath("/");
			
			response.addCookie(userCookie);
			response.addCookie(passCookie);
			response.addCookie(skIdObj);
		}else{//删除cookie
		 	Cookie killuid = new Cookie("uid",null);
		 	Cookie killupss = new Cookie("upss",null);
		 	Cookie skIdObj = new Cookie("skId",null);
		 	killuid.setMaxAge(0);
		 	killupss.setMaxAge(0);
		 	skIdObj.setMaxAge(0);
		 	
		 	killuid.setPath("/");
		 	killupss.setPath("/");
		 	skIdObj.setPath("/");
		 	response.addCookie(skIdObj);
		 	response.addCookie(killuid);			 	
		 	response.addCookie(killupss);
		}
		
	}
	
	
	
	/**
	 * 
	 * 功能: 输入用户名密码格式是否正确
	 * 作者: WXY
	 * 创建日期:2007-7-6
	 * @param username
	 * @param password
	 * @return
	 */
	private boolean isSyntax(String username,String password,HttpServletRequest request)
	{   
		String message="";
		boolean isPass=true;
		if(username == null || username.equals(""))
		{
			message = HintParameter.ERRORUSERNULL_DCPM;
			isPass=false;
		}
		if(!isPass)
			request.setAttribute(ParameterDic.MESSAGE, message);
		return isPass;
	}
//	
	/**
	 * 
	 * 功能: 判断是否是合法用户
	 *      非法用户返回 null
	 *      合法用户则返回改对象
	 * 作者: WXY
	 * 创建日期:2007-7-6
	 * @param username
	 * @param password
	 * @param service
	 * @return
	 */
	private UserBean isLegalityUser(String username,String password,HttpServletRequest request){
		password=MD5.md5(password);
//		ecpmUser=iValidateService.getUser(username, password);
		ValidateDao validateDao= new ValidateDao();
		return validateDao.findBean(username, password);
	}
	
	/**
	 * 
	 * 功能: 初始化超级用户
	 * 作者: WXY
	 */
	private void initAdministrator(HttpServletRequest request){
		HttpSession session=request.getSession();
		/**
		 * 
		 */
		session.setAttribute(ParameterDic.ISADMINISTRATOR, new Boolean(true));
		
		this.logger.info("超级管理员-*登录用户基本信息初始化完毕!");
		
	}
	
	/***
	 * 
	 * 功能: 验证通过之后初始化人员信息及其人员所在部门信息
	 *       存放个人信息session
	 * 作者: WXY
	 * 创建日期:2007-7-6
	 * @param username
	 * @param password
	 * @param service
	 * @param request
	 * @throws Exception 
	 */
	private void initUser(UserBean userBean,HttpServletRequest request) throws Exception{
		if(userBean==null)
			throw new Exception();
		HttpSession session=request.getSession();
		session.setAttribute(ParameterDic.USERSESSION, userBean);  //设置用户
	}
}